
#include"header/symbol.h"
#include<stdlib.h>
#include<string.h>

unsigned int sym_str_hash(char *str){
    unsigned int hash = 0;
    unsigned int x = 0;
    while(*str){
        hash = (hash << 4) + (*str++);
        if((x = hash & 0xF0000000)!=0){
            hash ^= (x >> 24);
            hash &= ~x;
        }
    }
    return (hash & 0x7FFFFFFF);
}

sym_table init_sym_table(sym_table pre,int size){
    sym_table table = (sym_table)calloc(1,sizeof(sym_table_));
    sym_entries entries = (sym_entries)calloc(size,sizeof(sym_entry));
    table->pre = pre;
    table->size = size;
    table->entrise = entries;
    return table;
}

sym_entry init_sym_entry(){
    sym_entry entry = (sym_entry)calloc(1,sizeof(sym_entry_));
    return entry;
}

sym_entry lookup_sym_entry(sym_table table,char * sym,int global){
    sym_table p = table;
    sym_entry e = NULL;
    sym_entry r = NULL;
    if(!global){
        e = p->entrise[sym_str_hash(sym)%(p->size)];
        while(e){
           if(!strcmp(e->sym,sym)){
               r = e;
               break;
           }
           e = e->next;
        }
        return r;
    }
    
    while(p){
        if(r) break;
        e = p->entrise[sym_str_hash(sym)%(p->size)];
        while(e){
           if(!strcmp(e->sym,sym)){
               r = e;
               break;
           }
           e = e->next;
        }
    }
    return r;
}

sym_entry insert_sym_entry(sym_table table,sym_entry entry){
    unsigned int idx = sym_str_hash(entry->sym)%(table->size);
    entry->next = table->entrise[idx];
    table->entrise[idx] = entry;
    return entry; 
}

